<template>
  <div class="container">
    <!-- 头部 -->
    <header class="header">
      <h1>共享社区</h1>
      <button class="upload-btn" @click="showUpload = true">+ 上传文件</button>
    </header>

    <!-- 文件展示区 -->
    <div class="file-grid">
      <div v-for="file in files" :key="file.id" class="file-card">
        <div class="file-thumbnail">
          <img v-if="file.type === 'image'" :src="file.url" alt="thumbnail">
          <video v-else-if="file.type === 'video'" :src="file.url" controls></video>
          <div v-else class="document-thumbnail">
            <i class="el-icon-document"></i>
          </div>
        </div>
        <div class="file-info">
          <h3>{{ file.title }}</h3>
          <p class="description">{{ file.description }}</p>
          <div class="meta">
            <span>{{ file.username }}</span>
            <span>{{ file.date }}</span>
          </div>
          <button class="download-btn" @click="downloadFile(file)">
            <i class="el-icon-download"></i> 下载
          </button>
        </div>
      </div>

      </div>
    <div style="margin-top: 20px; text-align: center">
      <el-pagination
          background
          :current-page="pageNum"
          :page-size="pageSize"
          :page-sizes="[9]"
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 上传文件弹窗 -->
    <el-dialog
        title="上传文件"
        :visible.sync="showUpload"
        @closed="resetForm"
        width="600px"
    >
      <div class="upload-form">
        <el-upload
            action="http://47.97.65.149:9090/project/upload"
            :before-upload="beforeFileUpload"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            :on-progress="handleFileProgress"
            :show-file-list="false"
            :headers="{ token: user.token }"


            :disabled="isUploading"
        >
          <el-button type="primary">
            <i class="el-icon-upload"></i>
            {{ newFile.fileUrl ? '已上传文件' : '点击上传文件' }}
          </el-button>
          <div v-if="isUploading" class="upload-progress">
            上传进度: {{ uploadPercent }}%
            <el-button type="text" @click.stop="cancelUpload">取消</el-button>
          </div>
        </el-upload>
        <div v-if="newFile.fileUrl" class="file-preview">
          <i class="el-icon-document"></i>
          {{ fileName }}
          <el-button type="text" @click="removeFile">移除</el-button>
        </div>

        <el-form label-width="80px">
          <el-form-item label="文件类型" required>
            <el-radio-group v-model="newFile.type">
              <el-radio label="file">文件</el-radio>
              <el-radio label="image">图片</el-radio>
              <el-radio label="video">视频</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="文件标题" required>
            <el-input
                v-model="newFile.title"
                placeholder="请输入文件标题"
            ></el-input>
          </el-form-item>

          <el-form-item label="文件描述">
            <el-input
                type="textarea"
                v-model="newFile.description"
                placeholder="请输入文件描述"
                :rows="3"
            ></el-input>
          </el-form-item>

          <el-form-item label="文件地址" v-if="newFile.fileUrl">
            <el-tag type="success">
              {{ newFile.fileUrl | truncate(30) }}
            </el-tag>
          </el-form-item>
        </el-form>

        <div class="dialog-footer">
          <el-button @click="showUpload = false">取消</el-button>
          <el-button
              type="primary"
              @click="submitUpload"
              :disabled="!formValid"
          >
            提交
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      // 新增上传相关状态
      isUploading: false,
      pageNum: 1,     // 当前页码
      pageSize: 9,    // 每页显示数量
      total: 0,        // 总数据量
      uploadController: null,
      fileName: '',
      fileList: [],
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      allowedExtensions: '.doc/.docx/.pdf/.jpg/.png/.mp4',
      showUpload: false,

      newFile: {
        type: 'file',
        title: '',
        description: '',
        fileUrl: '',
        file: null
      },
      files: [],
      uploadPercent: 0
    }
  },
  computed: {
    formValid() {
      return (
          this.newFile.type &&
          this.newFile.title.trim() &&
          this.newFile.fileUrl
      )
    }
  },
  created() {
    this.loadFiles()
  },
  methods: {

    async loadFiles() {
      try {
        const  response = await this.$request.get('/project/selectFeedbackAcceptance',{
          params: {  // 添加分页参数
            pageNum: this.pageNum,
                pageSize: this.pageSize
          }
        });
        this.files = response.data?.records || [];
        this.total = response.data?.total || 0;

      } catch (error) {
        console.error('获取文件列表失败:', error)
      }
    },
    handlePageChange(val) {
      this.pageNum = val;
      this.loadFiles();
    },
    beforeFileUpload(file) {
      const typeMapping = {
        'image/jpeg': 'image',
        'image/png': 'image',
        'video/mp4': 'video',
        'application/pdf': 'file',
        'application/msword': 'file',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'file'

      }

      const fileType = typeMapping[file.type]
      if (!fileType) {
        this.$message.error('不支持的文件类型')
        return false
      }

      if (this.newFile.type !== fileType) {
        this.$message.error('文件类型与选择类型不匹配')
        return false
      }

      // 新增上传控制
      this.newFile.file = file // 增加这行
      this.uploadController = new AbortController()
      this.isUploading = true
      this.uploadPercent = 0
      this.fileName = file.name
      return true
    },

    handleFileProgress(event) {
      this.uploadPercent = Math.round((event.loaded / event.total) * 100)
    },

    handleFileSuccess(response) {
      this.isUploading = false
      if (response.code === '200') {
        this.newFile.fileUrl = response.data
        this.$message.success('文件上传成功')

      } else {
        this.$message.error(response.msg)
      }
    },

    handleFileError() {
      this.isUploading = false
      this.$message.error('文件上传失败')
    },



    removeFile() {
      this.newFile.fileUrl = ''
      this.fileName = ''
      this.fileList = []
    },
    async submitUpload() {
      try {
        const  response = await this.$request.post('/project/addFile', {
          type: this.newFile.type,
          title: this.newFile.title,
          description: this.newFile.description,
          url: this.newFile.fileUrl,
          size: this.newFile.file?.size || 0,
          mimeType: this.newFile.file?.type || ''
        })


          this.showUpload = false
          this.$message.success('提交成功')
          this.resetForm()
          await this.loadFiles()

      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error(error.response?.data?.message || '提交失败')
      }
    },

    resetForm() {
      this.newFile = {
        type: 'file',
        title: '',
        description: '',
        fileUrl: '',
        file: null
      }
    },
    cancelUpload() {
      if (this.cancelUpload) {
        this.cancelUpload('用户取消上传')
      }
      this.isUploading = false
      this.uploadPercent = 0
      this.fileList = []
    },
    downloadFile(file) {
      const link = document.createElement('a')
      link.href = file.url
      link.download = file.title
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  },
  filters: {
    truncate(value, length) {
      if (!value) return ''
      return value.length > length
          ? value.substr(0, length) + '...'
          : value
    }
  }
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}
.upload-progress {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-preview {
  margin-top: 10px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.file-preview i {
  margin-right: 8px;
  font-size: 18px;
  color: #409eff;
}
.upload-btn {
  background: #ff5656;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  transition: background 0.3s;
}

.upload-btn:hover {
  background: #ff4444;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.file-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  overflow: hidden;
  transition: transform 0.2s;
}

.file-card:hover {
  transform: translateY(-5px);
}

.file-thumbnail {
  height: 200px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.file-thumbnail img,
.file-thumbnail video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.document-thumbnail {
  font-size: 60px;
  color: #666;
}

.file-info {
  padding: 15px;
}

.description {
  color: #666;
  font-size: 14px;
  margin: 10px 0;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.meta {
  display: flex;
  justify-content: space-between;
  color: #999;
  font-size: 12px;
  margin-bottom: 15px;
}

.download-btn {
  width: 100%;
  background: #f0f0f0;
  border: none;
  padding: 8px;
  border-radius: 5px;
  cursor: pointer;
  transition: background 0.3s;
}

.download-btn:hover {
  background: #e0e0e0;
}

.upload-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>